package com.ruoyi.system.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import com.ijpay.core.enums.SignType;
import com.ijpay.core.enums.TradeType;
import com.ijpay.core.kit.HttpKit;
import com.ijpay.core.kit.WxPayKit;
import com.ijpay.wxpay.WxPayApi;
import com.ijpay.wxpay.enums.WxApiType;
import com.ijpay.wxpay.model.ProfitSharingModel;
import com.ijpay.wxpay.model.ReceiverModel;
import com.ijpay.wxpay.model.RefundModel;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.SysConfigConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.pay.JsApiOrderModel;
import com.ruoyi.common.pay.MyWxPayConfig;
import com.ruoyi.common.pay.WxPayXiaoChengXuConfig;
import com.ruoyi.common.utils.CacheUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.vo.*;
import com.ruoyi.system.mapper.JiajiaMallOrderMapper;
import com.ruoyi.system.service.*;
import com.ruoyi.system.utils.PayUtil;
import com.ruoyi.system.utils.ProfileUtil;
import com.ruoyi.system.utils.TokenUtil;
import com.ruoyi.system.utils.V3PayUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;

@Service
public class ApiPayServiceImpl implements ApiPayService {
    private static final Logger logger = LoggerFactory.getLogger(ApiPayServiceImpl.class);

    //////////////////支付宝支付//////////////
    //APPID
    public static final  String app_id = "2021002193607091";
    //私钥
    public static final  String merchant_private_key = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCY1D1gQWUsrT4mZ2mBBK4tAFYK0ecSI1IE2MenSdrYwRdMETLtgog8mxDGgX5mHvbGVwrYpODx8SMvCScCpyCFlaRB1HWZrv7ny1XJOk+Xd6E7xbtzV3qWPq31Sl5qmQDRcSHhz7e6kRZiOAqR0AWYgRKccbocAZeoodsv0oriKQql+utEOURW/MAzEBrXKW9CD94EgPB6ByT077uJf9mDJTiR++AV48aj6iQZyU6+Va968urhihr0Hr3c3KkZrA7Wcs35RHOguhEtfsECt5fK/UQZDUYJP+5+2LjB93AqLsioopWa6Nusu5W3k6aqK32yG9/QreaOP1OitGIdviH7AgMBAAECggEABUzvKAR8ntUPX8OcbCYeaF8nnM505jMlaBegrROprHTd+vxpuMUbNobmSQw6tw4B3xUrwiHNz3ZekwYNPVFQlnF/Ne1JeuAP5TgvLICCPC2hAPK1sqVpEgbwf55psebGmX0EANH0fFsF3Lg23aHKX+SyIYzsOIZxnR6n/Huf54IZLPLRoHvkpxXVHWiEOsBTkijjy4OQsx+vjPbxx/awc9DMXQjUbM4kASLZS5cg73xLl7topxkebsLm8tHihUUP7wSU1wpfWeBACp63LH3LfkwqAf+YgvKpiAC2fGKzDOvYM71kGS/lzTJfve/MJKsDRUyg6H7eMXf6Lu423irSEQKBgQDGoBu88dtg8UhteTi6FV7NRzwlza0y88RUA2c0+oog1vv9jT4195E7WQnOAGeX2qF7gz8Z8R8Uf05PVhWVg0xPNp2m/7N/5wFkwI0zhCrFgoHqr1AYK9V77UgiB8xGeVZVXYgSjYgL1HEW4VUm9ie1LV3I3AdbRBOqUJAQZV7kiQKBgQDE+ZicqV5SyYyn9QMBVQtbTug5A23KD5804e9h2kEFih6fnOCjvWZjR2bDhcsS1gzUy4161d0rL5+yeLfVZnEuxxTNXeR6D5ZxwwR/R7Ra436Uv7e3NT6xyjA88+zU0CrhCdN2fFDR+WInZ1vipkG8GC6UhSzxSpoTFmexTA95YwKBgQC3l8yr1B6EN+JLlk3x6sjrE9or0zYxr5KcWVzvYlmEy1K25fRH6+KpKb7fVA5tFaBHy2PrNa4Vwyp+OMLQpUFGwuPsNdQT+FGYcEbUBGmIkP5HD+8HuJSm7QfMtMqDpapAU6jwBTRoQuCZVoTf8412cU2L2J1QJdfLiJXxIdIZiQKBgQCAUCe+RgaP34OlFdJzV7ciL/DO0xD+A9cuV8/c6pRYy3TPfR5JC+Ra3/RtggabqpyJMmBjmFWPAGMDm+gFN8qbMky2y2c+rFDQor2XPFqcqn2W4J0I18KThqaNzkiFCWYlWoVKNglf/xiVmpsctjk0Enyle2ufc32S2ZGKyYV7CQKBgAWtLSpozvvStYoZXUcM/d3TxRrAwiH5Z9j+SEkyuwIAHHzAM/5CNX1F7eBwvBHUEbe/ovpkV5hYrtJJFooXAHYAjnKOifrGSLTCJk8JcHbOpW7FJyaN/mgqAOS2+BEL20ni+/DCo7k04r0n98fAiSIyXicRFbB5LQbHQLUKQAKg";
    //支付宝公钥
    public static final  String alipay_public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmNQ9YEFlLK0+JmdpgQSuLQBWCtHnEiNSBNjHp0na2MEXTBEy7YKIPJsQxoF+Zh72xlcK2KTg8fEjLwknAqcghZWkQdR1ma7+58tVyTpPl3ehO8W7c1d6lj6t9UpeapkA0XEh4c+3upEWYjgKkdAFmIESnHG6HAGXqKHbL9KK4ikKpfrrRDlEVvzAMxAa1ylvQg/eBIDwegck9O+7iX/ZgyU4kfvgFePGo+okGclOvlWvevLq4Yoa9B693NypGawO1nLN+URzoLoRLX7BAreXyv1EGQ1GCT/ufti4wfdwKi7IqKKVmujbrLuVt5Omqit9shvf0K3mjj9TorRiHb4h+wIDAQAB";
    //网关地址
    public static final  String gatewayUrl = "https://openapi.alipay.com/gateway.do";

    @Autowired
    private IJiajiaTransferAccountsService jiajiaTransferAccountsService;
    @Autowired
    private IJiajiaOrderService orderService;

    @Autowired
    private IJiajiaMallOrderService mallOrderService;


    @Autowired
    private IJiajiaOrderTimeService orderTimeService;

    @Autowired
    private IJiajiaChongzhiRecordService recordService;

    @Autowired
    private WxPayXiaoChengXuConfig wxPayXiaoChengXuConfig;

    @Autowired
    private MyWxPayConfig myWxPayConfig;
    @Autowired
    private PayUtil payUtil;
    @Autowired
    private IJiajiaItemService iJiajiaItemService;

    @Autowired
    private IJiajiaMailOrderDetailService iJiajiaMailOrderDetailService;

    @Autowired
    private IJiajiaProxyApplicationService iJiajiaProxyApplicationService;
    @Autowired
    private JiajiaMallOrderMapper jiajiaMallOrderMapper;
    @Autowired
    private IJiajiaUserService userService;
    @Autowired
    private IJiajiaPointsFlowService jiajiaPointsFlowService;

    @Autowired
    private  IJiajiaProxyApplicationService jiajiaProxyApplicationService;





    @Override
    public AjaxResult xiaoChengXuPay(String orderSn, String jsCode) {

        JiajiaUser user = userService.selectJiajiaUserById(TokenUtil.getUid());
        if (user == null)return AjaxResult.notLogin();

        JiajiaOrder order = new JiajiaOrder();
        order.setOrderSn(orderSn);
        List<JiajiaOrder> orderList = orderService.selectJiajiaOrderList(order);

        if (orderList.isEmpty())return AjaxResult.refreshAgain();

        order = orderList.get(0);
        JiajiaOrderTime jiajiaOrderTime = new JiajiaOrderTime();
        jiajiaOrderTime.setOrderSn(order.getOrderSn());
        List<JiajiaOrderTime> orderTimeList = orderTimeService.selectJiajiaOrderTimeList(jiajiaOrderTime);
        if (ObjectUtil.isNotEmpty(orderTimeList)) {//获取预约时间最早的一个时间
            JiajiaOrderTime orderTime = orderTimeList.get(0);
            String dayTime = orderTime.getDay()+" "+orderTime.getStartTime()+":00";
            Date startTime = DateUtils.parseDate(dayTime);
            if (startTime.before(new Date())){
                order.setStatus(7);
                orderService.updateJiajiaOrder(order);
                return AjaxResult.error("预约时间已过，请重新预约下单!");
            }
        }
        //订单项目详情
        JiajiaItem jiajiaItem = iJiajiaItemService.selectJiajiaItemById(order.getIid());
        if(jiajiaItem == null){
            return AjaxResult.error("项目信息不存在");
        }
        PayParametersVo payParametersVo = new PayParametersVo();
        payParametersVo.setBody(jiajiaItem.getName());
        payParametersVo.setTotalFee(String.valueOf((order.getTotalPrice().multiply(new BigDecimal("100"))).intValue()));
        payParametersVo.setOutTradeNo(order.getOrderSn());
        payParametersVo.setNotifyUrl(wxPayXiaoChengXuConfig.getNotifyUrl()+"/api/paynotify/wxItemPayNotice");
        return payExcute(payParametersVo,user);
    }



    public AjaxResult payExcute (PayParametersVo payParametersVo,JiajiaUser user){
        String platForms = TokenUtil.getPlatForms();
        logger.info(platForms);

        if(TokenUtil.platforms_MP.equals(platForms) ){
            logger.info("小程序发起支付");
            payParametersVo.setOpenId(user.getOpenId()); ;
            payParametersVo.setAppid(wxPayXiaoChengXuConfig.getAppid());;
        }else if(TokenUtil.platforms_H5.equals(platForms) ){
            logger.info("H5发起支付");
            payParametersVo.setOpenId(user.getGzhOpenId()); ;
            payParametersVo.setAppid(wxPayXiaoChengXuConfig.getH5Appid());;
        }
        JsApiOrderModel baseModel = new JsApiOrderModel();
        baseModel.setAppid(payParametersVo.getAppid());
        baseModel.setMch_id(wxPayXiaoChengXuConfig.getMachid());
        baseModel.setNonce_str(WxPayKit.generateStr());
        baseModel.setBody(payParametersVo.getBody());
        baseModel.setOut_trade_no(payParametersVo.getOutTradeNo());
        baseModel.setTotal_fee(payParametersVo.getTotalFee());
        baseModel.setNotify_url(payParametersVo.getNotifyUrl());
        baseModel.setTrade_type(TradeType.JSAPI.getTradeType());
        baseModel.setProfit_sharing("Y");
        if (ProfileUtil.getActiveProfile().equals(ProfileUtil.PROFILE_DEV) || Convert.toInt(user.getIsTest(), 0) == 1){
            baseModel.setTotal_fee("1");
        }
        baseModel.setOpenid(payParametersVo.getOpenId());
        logger.info(">>>baseModel>>>>>"+ JSON.toJSONString(baseModel));
        Map<String, String> params =  baseModel.createSign(wxPayXiaoChengXuConfig.getMckKey(), SignType.MD5);

        //进行数据加密封装
        String xmlResult = WxPayApi.pushOrder(false, params);
        logger.info(xmlResult);

        Map<String, String> resultMap = WxPayKit.xmlToMap(xmlResult);
        if (StringUtils.equals(resultMap.get("return_code"), "SUCCESS")) {
            String prepayId = resultMap.get("prepay_id");
            Map<String, String> packageParams = WxPayKit.prepayIdCreateSign(prepayId, payParametersVo.getAppid(),
                    wxPayXiaoChengXuConfig.getMckKey(), SignType.MD5);
            // 微信浏览器中拿此参数调起支付
            return AjaxResult.success(packageParams);

        }
        logger.info(">>>>return_msg>>>"+resultMap.get("return_msg"));
        return AjaxResult.error(resultMap.get("return_msg"));    }


    @Override
    @Transactional(isolation = Isolation.SERIALIZABLE)
    public AjaxResult xiaoChengXuMallPay(String orderSn, String jsCode) {
        JiajiaUser user = userService.selectJiajiaUserById(TokenUtil.getUid());
        if (user == null)return AjaxResult.notLogin();


        JiajiaMallOrderVo jiajiaMallOrder = mallOrderService.selectJiajiaMallOrderById(Long.valueOf(orderSn));

        if (!Optional.ofNullable(jiajiaMallOrder).isPresent())
        {
            return AjaxResult.refreshAgain();
        }
        PayParametersVo payParametersVo = new PayParametersVo();
        payParametersVo.setTotalFee(String.valueOf((jiajiaMallOrder.getTotalPrice().multiply(new BigDecimal("100"))).intValue()));
        payParametersVo.setBody("商城"+jiajiaMallOrder.getOrderDescription());
        payParametersVo.setOutTradeNo(jiajiaMallOrder.getOrderNum());
        payParametersVo.setNotifyUrl(wxPayXiaoChengXuConfig.getNotifyUrl()+"/api/paynotify/wxMallPayNotice");
        return payExcute(payParametersVo,user);


    }

    @Override
    public AjaxResult xiaoChengXuProxyPay(String id, String jsCode) {
        JiajiaUser user = userService.selectJiajiaUserById(TokenUtil.getUid());
        if (user == null)return AjaxResult.notLogin();

        JiajiaProxyApplication jiajiaProxyApplication = iJiajiaProxyApplicationService.selectJiajiaProxyApplicationById(Long.valueOf(id));

        if (!Optional.ofNullable(jiajiaProxyApplication).isPresent())
        {
            return AjaxResult.refreshAgain();
        }
        PayParametersVo payParametersVo = new PayParametersVo();

        if(jiajiaProxyApplication.getType()==0){
            Object cost = CacheUtils.get(Constants.SYS_CONFIG_CACHE, Constants.SYS_CONFIG_KEY+SysConfigConstants.sys_apply_promoter_cost);

            payParametersVo.setTotalFee(cost.toString());

        }else{
            Object cost = CacheUtils.get(Constants.SYS_CONFIG_CACHE, Constants.SYS_CONFIG_KEY+SysConfigConstants.sys_apply_community_cost);

            payParametersVo.setTotalFee(cost.toString());

        }
        payParametersVo.setBody("推广代理收入");
        payParametersVo.setOutTradeNo(jiajiaProxyApplication.getId().toString());
        payParametersVo.setNotifyUrl(wxPayXiaoChengXuConfig.getNotifyUrl()+"/api/paynotify/wxProxyPayNotice");
        return payExcute(payParametersVo,user);
    }

    @Override
    public AjaxResult proxyProfitSharingByImpl(String orderSn) {
        JiajiaProxyApplication jiajiaProxyApplication = iJiajiaProxyApplicationService.selectJiajiaProxyApplicationById(Long.valueOf(orderSn));
        Object o = CacheUtils.get(Constants.SYS_CONFIG_CACHE, Constants.SYS_CONFIG_KEY+ SysConfigConstants.sys_promotion_promoter);

        JiajiaUser jiajiaUser = userService.selectJiajiaUserById(jiajiaProxyApplication.getUserId());
        JiajiaUser jiajiaUser1 = userService.selectjiajiaUser(jiajiaUser.getInviter());
       profitSharingByProxy(jiajiaUser1.getOpenId(),Integer.valueOf(o.toString()),jiajiaProxyApplication.getTransactionId(), jiajiaProxyApplication.getId().toString());
        return AjaxResult.success();
    }

    @Override
    public AjaxResult xiaoChengXuMallRefund(String orderSn, String jsCode) {

        JiajiaMallOrderVo jiajiaMallOrderVo = jiajiaMallOrderMapper.selectJiajiaMallOrderById(Long.valueOf(orderSn));

        //这里是走小程序退款
        Map<String, String> params = RefundModel.builder()
                .appid(wxPayXiaoChengXuConfig.getAppid())
                .mch_id(wxPayXiaoChengXuConfig.getMachid())
                .nonce_str(WxPayKit.generateStr())
                .out_trade_no(jiajiaMallOrderVo.getOrderNum())
                .out_refund_no(jiajiaMallOrderVo.getOrderNum())
                .transaction_id(jiajiaMallOrderVo.getTransactionId())
                .total_fee(String.valueOf(jiajiaMallOrderVo.getTotalPrice().multiply(new BigDecimal("100")).intValue()))
                .refund_fee(String.valueOf(jiajiaMallOrderVo.getActualPrice().multiply(new BigDecimal("100")).intValue()))
                .notify_url(wxPayXiaoChengXuConfig.getNotifyUrl()+"/api/paynotify/mallRefundNotify")
                .build()
                .createSign(wxPayXiaoChengXuConfig.getMckKey(), SignType.MD5);
                InputStream certIs = null;
        try {
            ClassPathResource classPathResource = new ClassPathResource(wxPayXiaoChengXuConfig.getKeyPath());
            certIs = classPathResource.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String refundStr = WxPayApi.orderRefundByProtocol(false, params, wxPayXiaoChengXuConfig.getKeyPath(), wxPayXiaoChengXuConfig.getMachid(),"");
        logger.info(refundStr);

        Map<String,String> map = WxPayKit.xmlToMap(refundStr);
        String returnCode = map.get("return_code");
        String resultCode = map.get("result_code");
        if (!resultCode.equals("SUCCESS") || !returnCode.equals("SUCCESS")){
            throw new RuntimeException("退款失败");
        }
        return AjaxResult.success();
    }


    @Override
    public AjaxResult xiaoChengXuPayChongZhi(String chongZhiSn, String jsCode) {


        JiajiaUser user = userService.selectJiajiaUserById(TokenUtil.getUid());
        if (user == null)return AjaxResult.notLogin();

        JiajiaChongzhiRecord record = new JiajiaChongzhiRecord();
        record.setChongZhiSn(chongZhiSn);
        List<JiajiaChongzhiRecord> recordList = recordService.selectJiajiaChongzhiRecordList(record);

        if (recordList.isEmpty())return AjaxResult.refreshAgain();

        record = recordList.get(0);
        if (record.getStatus().intValue() == 1)return AjaxResult.refreshAgain();

        String openId = payUtil.getWxOpenIdByJsCode(jsCode);
        if (!StringUtils.isEmpty(openId)){
            user.setOpenId(openId);
            userService.updateJiajiaUser(user);
        }else {
            openId = user.getOpenId();
        }

        if (StringUtils.isEmpty(openId)){
            return AjaxResult.error("缺少必要参数");
        }

        JsApiOrderModel baseModel = new JsApiOrderModel();
        baseModel.setAppid(wxPayXiaoChengXuConfig.getAppid());
        baseModel.setMch_id(wxPayXiaoChengXuConfig.getMachid());
        baseModel.setNonce_str(WxPayKit.generateStr());
        baseModel.setBody("微信支付");
        baseModel.setOut_trade_no(record.getChongZhiSn());
        baseModel.setTotal_fee(String.valueOf((record.getChongZhi().multiply(new BigDecimal("100"))).intValue()));
        baseModel.setNotify_url(wxPayXiaoChengXuConfig.getNotifyUrl()+"/api/paynotify/wxmallPayChongZhiNotice");
        baseModel.setTrade_type(TradeType.JSAPI.getTradeType());
        if (ProfileUtil.getActiveProfile().equals(ProfileUtil.PROFILE_DEV) || Convert.toInt(user.getIsTest(), 0) == 1){
            baseModel.setTotal_fee("1");//1分
        }
        baseModel.setOpenid(openId);
        Map<String, String> params =  baseModel.createSign(wxPayXiaoChengXuConfig.getMckKey(), SignType.MD5);

        //进行数据加密封装
        String xmlResult = WxPayApi.pushOrder(false, params);
        Map<String, String> resultMap = WxPayKit.xmlToMap(xmlResult);
        if (StringUtils.equals(resultMap.get("return_code"), "SUCCESS")) {
            String prepayId = resultMap.get("prepay_id");
            Map<String, String> packageParams = WxPayKit.prepayIdCreateSign(prepayId, wxPayXiaoChengXuConfig.getAppid(),
                    wxPayXiaoChengXuConfig.getMckKey(), SignType.MD5);
            // 微信浏览器中拿此参数调起支付
            return AjaxResult.success(packageParams);

        }

        return AjaxResult.error("支付失败");
    }

    @Override
    public AjaxResult weiXinPay(String orderSn, String ip) {

        JiajiaUser user = userService.selectJiajiaUserById(TokenUtil.getUid());
        if (user == null)return AjaxResult.notLogin();

        JiajiaOrder order = new JiajiaOrder();
        order.setOrderSn(orderSn);
        List<JiajiaOrder> orderList = orderService.selectJiajiaOrderList(order);

        if (orderList.isEmpty())return AjaxResult.refreshAgain();

        order = orderList.get(0);

        JiajiaOrderTime jiajiaOrderTime = new JiajiaOrderTime();
        jiajiaOrderTime.setOrderSn(order.getOrderSn());
        List<JiajiaOrderTime> orderTimeList = orderTimeService.selectJiajiaOrderTimeList(jiajiaOrderTime);
        if (ObjectUtil.isNotEmpty(orderTimeList)) {//获取预约时间最早的一个时间
            JiajiaOrderTime orderTime = orderTimeList.get(0);
            String dayTime = orderTime.getDay()+" "+orderTime.getStartTime()+":00";
            Date startTime = DateUtils.parseDate(dayTime);
            if (startTime.before(new Date())){
                order.setStatus(7);
                orderService.updateJiajiaOrder(order);
                return AjaxResult.error("预约时间已过，请重新下单!");
            }
        }


        String payMoney = order.getTotalPrice().multiply(new BigDecimal("100"))
                .stripTrailingZeros().toPlainString();
        if (ProfileUtil.getActiveProfile().equals(ProfileUtil.PROFILE_DEV) || Convert.toInt(user.getIsTest(), 0) == 1){
            payMoney = "1";
        }
        try {
            WXPay wxPay = new WXPay(myWxPayConfig);

            //orderNum商户系统内部订单号，要求32个字符内，只能是数字、大小写字母_-|*且在同一个商户号下唯一。
            //商品描述交易字段格式根据不同的应用场景按照以下格式：APP——需传入应用市场上的APP名字-实际商品名称，天天爱消除-游戏充值。
            String body = "XX-" + "家家到家-上门服务";

            //根据微信支付api来设置
            Map<String, String> data = new HashMap<>();
            data.put("appid", myWxPayConfig.getAppID());//微信开放平台审核通过的应用APPID
            data.put("mch_id", myWxPayConfig.getMchID()); //微信支付分配的商户号
            data.put("trade_type", "APP"); //支付场景 APP 微信app支付 JSAPI 公众号支付  NATIVE 扫码支付
            data.put("notify_url", wxPayXiaoChengXuConfig.getNotifyUrl()+"/api/paynotify/wxPayNotice");                     //回调地址
            data.put("spbill_create_ip", ip);             //终端ip
            data.put("total_fee", payMoney);       //订单总金额
            data.put("out_trade_no", order.getOrderSn());   //商户平台生成的唯一订单号
            data.put("body", body);
            data.put("nonce_str", WXPayUtil.generateNonceStr());   // 随机字符串，不长于32位
            data.put("sign", WXPayUtil.generateSignature(data, myWxPayConfig.getKey()));//签名

            /** wxService.unifiedOrder 这个方法中调用微信统一下单接口 */
            Map<String, String> respData;

            respData = wxPay.unifiedOrder(data);

            if (respData.get("return_code").equals("SUCCESS")) {

                //二次签名
                //这里就是重点了，当时也是在这里卡了很久。统一下单成功之后，拿到微信后台返回结果.再次计算签名，
                //而且注意的是二次签名和统一下单的时候计算签名的参数名不相同，也就是下面这些参数。
                //当时做的时候不晓得要二次签名，就直接把统一下单的签名返回给前端，再调起微信支付，结果一直返回-1
                String time = (System.currentTimeMillis() + "").substring(0, 10);//时间戳，必须是10位的
                //返回给APP端的参数，APP端再调起支付接口
                Map<String, String> repData = new HashMap<>();
                repData.put("appid", myWxPayConfig.getAppID());//appid
                repData.put("partnerid", myWxPayConfig.getMchID());//mchId
                repData.put("prepayid", respData.get("prepay_id"));//统一下单成成之后返回的prepay_id
                repData.put("package", "Sign=WXPay");//直接写死的
                repData.put("noncestr", respData.get("nonce_str"));//统一下单成功之后返回的nonce_str
                repData.put("timestamp", time);

                String sign = WXPayUtil.generateSignature(repData, myWxPayConfig.getKey());//再次计算签名
                repData.put("sign",sign);

                //将repDate返回给前端，就可以支付了
                return AjaxResult.success(repData);

            }
            return AjaxResult.error("支付失败");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("支付失败");
        }
    }

    @Override
    public AjaxResult WxPayChongZhi(String chongZhiSn, String ip) {
        JiajiaUser user = userService.selectJiajiaUserById(TokenUtil.getUid());
        if (user == null)return AjaxResult.notLogin();

        JiajiaChongzhiRecord record = new JiajiaChongzhiRecord();
        record.setChongZhiSn(chongZhiSn);
        List<JiajiaChongzhiRecord> recordList = recordService.selectJiajiaChongzhiRecordList(record);

        if (recordList.isEmpty())return AjaxResult.refreshAgain();

        record = recordList.get(0);
        if (record.getStatus().intValue() == 1)return AjaxResult.refreshAgain();

        String payMoney = record.getChongZhi().multiply(new BigDecimal("100"))
                .stripTrailingZeros().toPlainString();
        if (ProfileUtil.getActiveProfile().equals(ProfileUtil.PROFILE_DEV) || Convert.toInt(user.getIsTest(), 0) == 1){
            payMoney = "1";//测试实际支付为1分钱
        }
        try {
            WXPay wxPay = new WXPay(myWxPayConfig);

            //orderNum商户系统内部订单号，要求32个字符内，只能是数字、大小写字母_-|*且在同一个商户号下唯一。
            //商品描述交易字段格式根据不同的应用场景按照以下格式：APP——需传入应用市场上的APP名字-实际商品名称，天天爱消除-游戏充值。
            String body = "XX-" + "百吉星社工-上门服务";

            //根据微信支付api来设置
            Map<String, String> data = new HashMap<>();
            data.put("appid", myWxPayConfig.getAppID());//微信开放平台审核通过的应用APPID
            data.put("mch_id", myWxPayConfig.getMchID()); //微信支付分配的商户号
            data.put("trade_type", "APP"); //支付场景 APP 微信app支付 JSAPI 公众号支付  NATIVE 扫码支付
            data.put("notify_url", wxPayXiaoChengXuConfig.getNotifyUrl()+"/api/paynotify/wxPayChongZhiNotice");                     //回调地址
            data.put("spbill_create_ip", ip);             //终端ip
            data.put("total_fee", payMoney);       //订单总金额
            data.put("out_trade_no", record.getChongZhiSn());   //商户平台生成的唯一订单号
            data.put("body", body);
            data.put("nonce_str", WXPayUtil.generateNonceStr());   // 随机字符串，不长于32位
            data.put("sign", WXPayUtil.generateSignature(data, myWxPayConfig.getKey()));//签名

            /** wxService.unifiedOrder 这个方法中调用微信统一下单接口 */
            Map<String, String> respData;

            respData = wxPay.unifiedOrder(data);

            if (respData.get("return_code").equals("SUCCESS")) {

                //二次签名
                //这里就是重点了，当时也是在这里卡了很久。统一下单成功之后，拿到微信后台返回结果.再次计算签名，
                //而且注意的是二次签名和统一下单的时候计算签名的参数名不相同，也就是下面这些参数。
                //当时做的时候不晓得要二次签名，就直接把统一下单的签名返回给前端，再调起微信支付，结果一直返回-1
                String time = (System.currentTimeMillis() + "").substring(0, 10);//时间戳，必须是10位的
                //返回给APP端的参数，APP端再调起支付接口
                Map<String, String> repData = new HashMap<>();
                repData.put("appid", myWxPayConfig.getAppID());//appid
                repData.put("partnerid", myWxPayConfig.getMchID());//mchId
                repData.put("prepayid", respData.get("prepay_id"));//统一下单成成之后返回的prepay_id
                repData.put("package", "Sign=WXPay");//直接写死的
                repData.put("noncestr", respData.get("nonce_str"));//统一下单成功之后返回的nonce_str
                repData.put("timestamp", time);

                String sign = WXPayUtil.generateSignature(repData, myWxPayConfig.getKey());//再次计算签名
                repData.put("sign",sign);

                //将repDate返回给前端，就可以支付了
                return AjaxResult.success(repData);

            }
            return AjaxResult.error("支付失败");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("支付失败");

        }
    }

    @Override
    public AjaxResult zhiFuBaoPay(String orderSn) {
        JiajiaOrder order = new JiajiaOrder();
        order.setOrderSn(orderSn);
        List<JiajiaOrder> orderList = orderService.selectJiajiaOrderList(order);

        if (orderList.isEmpty())return AjaxResult.refreshAgain();

        order = orderList.get(0);

        JiajiaOrderTime jiajiaOrderTime = new JiajiaOrderTime();
        jiajiaOrderTime.setOrderSn(order.getOrderSn());
        List<JiajiaOrderTime> orderTimeList = orderTimeService.selectJiajiaOrderTimeList(jiajiaOrderTime);
        if (ObjectUtil.isNotEmpty(orderTimeList)) {//获取预约时间最早的一个时间
            JiajiaOrderTime orderTime = orderTimeList.get(0);
            String dayTime = orderTime.getDay()+" "+orderTime.getStartTime()+":00";
            Date startTime = DateUtils.parseDate(dayTime);
            if (startTime.before(new Date())) {
                return AjaxResult.error("预约时间已过，请重新下单!");
            }
        }

        if (ProfileUtil.getActiveProfile().equals(ProfileUtil.PROFILE_DEV)){
        }

        AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl,
                app_id,
                merchant_private_key,
                "json",
                "utf-8",
                alipay_public_key,
                "RSA2");
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setBody("百吉星社工");
        model.setSubject("百吉星社工");
        model.setOutTradeNo(orderSn);
        model.setTimeoutExpress("30m");
        model.setTotalAmount(order.getRealPrice().setScale(2, RoundingMode.HALF_UP)+"");
        if (ProfileUtil.getActiveProfile().equals(ProfileUtil.PROFILE_DEV)){
            model.setTotalAmount("0.01");
        }
        model.setProductCode("QUICK_MSECURITY_PAY");
        request.setBizModel(model);
        request.setNotifyUrl(wxPayXiaoChengXuConfig.getNotifyUrl()+"/api/paynotify/aliAppPayNotify");
        AlipayTradeAppPayResponse response = null;
        try {
            response = alipayClient.sdkExecute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
            System.out.println(response.getBody());
        } else {
            System.out.println("调用失败");
            return AjaxResult.error("支付宝调用失败，请重试！");
        }

        return AjaxResult.success("获取成功",response.getBody());
    }

    @Override
    public AjaxResult zhiFuBaoChongZhiPay(String chongZhiSn) {


        JiajiaChongzhiRecord record = new JiajiaChongzhiRecord();
        record.setChongZhiSn(chongZhiSn);
        List<JiajiaChongzhiRecord> recordList = recordService.selectJiajiaChongzhiRecordList(record);

        if (recordList.isEmpty())return AjaxResult.refreshAgain();

        record = recordList.get(0);
        if (record.getStatus().intValue() == 1)return AjaxResult.refreshAgain();


        if (ProfileUtil.getActiveProfile().equals(ProfileUtil.PROFILE_DEV)){
        }

        AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl,
                app_id,
                merchant_private_key,
                "json",
                "utf-8",
                alipay_public_key,
                "RSA2");
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setBody("百吉星社工-充值");
        model.setSubject("百吉星社工-充值");
        model.setOutTradeNo(chongZhiSn);
        model.setTimeoutExpress("30m");
        model.setTotalAmount(record.getChongZhi().setScale(2,RoundingMode.HALF_UP)+"");
        if (ProfileUtil.getActiveProfile().equals(ProfileUtil.PROFILE_DEV)){
            model.setTotalAmount("0.01");
        }
        model.setProductCode("QUICK_MSECURITY_PAY");
        request.setBizModel(model);
        request.setNotifyUrl(wxPayXiaoChengXuConfig.getNotifyUrl()+"/api/paynotify/aliAppPayChongZhiNotify");
        AlipayTradeAppPayResponse response = null;
        try {
            response = alipayClient.sdkExecute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
            System.out.println(response.getBody());
        } else {
            System.out.println("调用失败");
            return AjaxResult.error("支付宝调用失败，请重试！");
        }

        return AjaxResult.success("获取成功",response.getBody());

    }

    @Override
    public String profitSharingAddReceiver(String openid) {


        ReceiverModel receiver = ReceiverModel.builder()
                .type("PERSONAL_OPENID")
                .account(openid)
                .relation_type("PARTNER")
                .build();
        Map<String, String> params = ProfitSharingModel.builder()
                .mch_id(myWxPayConfig.getMchID())
                .appid(myWxPayConfig.getAppID())
                .nonce_str(WxPayKit.generateStr())
                .receiver(JSON.toJSONString(receiver))
                .build()
                .createSign(wxPayXiaoChengXuConfig.getMckKey(), SignType.HMACSHA256);
        logger.info("请求参数:{}", WxPayKit.toXml(params));
        String result = WxPayApi.profitSharingAddReceiver(params);
        System.out.println(result);
        String[] split = result.split("</result_code>");
        String[] split1 = split[0].split("<result_code>");
        if (split1[1].equals("<![CDATA[FAIL]]>")){
            String[] strings = result.split("</err_code_des>");
            String[] strings1 = strings[0].split("<err_code_des>");
            System.out.println(strings1[1]);
            throw new RuntimeException(strings1[1]);
        }
        logger.info("请求结果:{}", result);
        return JSON.toJSONString(WxPayKit.xmlToMap(result));


    }



    @Override
    public String profitSharing(JiajiaOrder order ,List<Map <String,String>> list) {

        List<ReceiverModel> listReceiver = new ArrayList<>();
        list.stream().forEach(map ->{
            logger.info("price:"+Double.valueOf(map.get("price")).intValue());
            ReceiverModel build = ReceiverModel.builder()
                    .type("PERSONAL_OPENID")
                    .account(map.get("openId"))
                    .amount(Double.valueOf(map.get("price")).intValue())
                    .description("订单号:"+order.getOrderSn()+"分账类型"+map.get("type")+"分账")
                    .build();
            listReceiver.add(build);


        });

        Map<String, String> params = ProfitSharingModel.builder()
                .mch_id(myWxPayConfig.getMchID())
                .appid(myWxPayConfig.getAppID())
                .nonce_str(WxPayKit.generateStr())
                .transaction_id(order.getTransactionId())
                .out_order_no(order.getOrderSn())
                .receivers(JSON.toJSONString(listReceiver))
                .build()
                .createSign(wxPayXiaoChengXuConfig.getMckKey(), SignType.HMACSHA256);

        logger.info("请求参数:{}", WxPayKit.toXml(params));
        //String result = WxPayApi.profitSharing(params, wxPayXiaoChengXuConfig.getKeyPath(), myWxPayConfig.getMchID());
        String refundStr = HttpKit.getDelegate().post(WxPayApi.getReqUrl(WxApiType.PROFIT_SHARING), WxPayKit.toXml(params), wxPayXiaoChengXuConfig.getKeyPath(), myWxPayConfig.getMchID(), "");

        logger.info("请求结果:{}", refundStr);
        return JSON.toJSONString(WxPayKit.xmlToMap(refundStr));

    }

    @Override
    public String profitsharingQuery(String orderSn) {
        JiajiaOrder order =new JiajiaOrder();
        order.setOrderSn(orderSn);
        JiajiaOrder jiajiaOrder = orderService.selectJiajiaOrderList(order).get(0);
        Map<String, String> params = ProfitSharingModel.builder()
                .mch_id(myWxPayConfig.getMchID())
                .appid(myWxPayConfig.getAppID())
                .nonce_str(WxPayKit.generateStr())
                .transaction_id(jiajiaOrder.getTransactionId())
                .out_order_no(jiajiaOrder.getOrderSn())
                .build()
                .createSign(wxPayXiaoChengXuConfig.getMckKey(), SignType.MD5);
        return WxPayApi.profitSharingQuery(params);
    }

    @Override
    public String profitsharingReturn(String orderSn,String type) {
        String transaction_id="";
        String out_order_no="";
        String order_id="";
        String open_id="";
        String return_amount="";


        if("1".equals(type)){
            //服务回退

            JiajiaOrder jiajiaOrder = orderService.selectJiajiaOrderById(Long.valueOf(orderSn));
            transaction_id=jiajiaOrder.getTransactionId();
            out_order_no=jiajiaOrder.getOrderSn();
        }else if("2".equals(type)){
            //商城回退
            JiajiaMallOrderVo jiajiaMallOrderVo = jiajiaMallOrderMapper.selectJiajiaMallOrderById(Long.valueOf(orderSn));
            transaction_id=jiajiaMallOrderVo.getTransactionId();
            out_order_no=jiajiaMallOrderVo.getOrderNum();
        }else {
           //代理回退
            JiajiaProxyApplication jiajiaProxyApplication = iJiajiaProxyApplicationService.selectJiajiaProxyApplicationById(Long.valueOf(orderSn));
            JiajiaUser jiajiaUser = userService.selectJiajiaUserById(jiajiaProxyApplication.getUserId());
            JiajiaUser jiajiaUser1 = userService.selectjiajiaUser(jiajiaUser.getPhone());
            open_id=jiajiaUser1.getOpenId();
            transaction_id=jiajiaProxyApplication.getTransactionId();
            out_order_no=orderSn;
            order_id=jiajiaProxyApplication.getProfitSharingId();
            return_amount = CacheUtils.get(Constants.SYS_CONFIG_CACHE, Constants.SYS_CONFIG_KEY+ SysConfigConstants.sys_promotion_promoter).toString();

        }
        logger.info("分账回退order_id："+order_id);

        BjxProfitSharingModel personal_openid = BjxProfitSharingModel.builder()
                .mch_id(myWxPayConfig.getMchID())
                .appid(myWxPayConfig.getAppID())
                .nonce_str(WxPayKit.generateStr())
                .order_id(order_id)
                .out_return_no(WxPayKit.generateStr())
                .build();
        personal_openid.setReturn_account(open_id);
        personal_openid.setReturn_account_type("MERCHANT_ID");
        personal_openid.setReturn_amount(return_amount);

        Map<String, String> params = personal_openid.createSign(wxPayXiaoChengXuConfig.getMckKey(), SignType.MD5);

        logger.info("分账回退请求："+ WxPayKit.toXml(params));

        String refundStr = HttpKit.getDelegate().post(WxPayApi.getReqUrl(WxApiType.PROFIT_SHARING_RETURN), WxPayKit.toXml(params), wxPayXiaoChengXuConfig.getKeyPath(), myWxPayConfig.getMchID(), "");
        logger.info("分账回退结果："+refundStr);
        return refundStr;

    }

    @Override
    public String profitsharingReturnQuery(String orderSn) {
        JiajiaOrder order =new JiajiaOrder();
        order.setOrderSn(orderSn);
        JiajiaOrder jiajiaOrder = orderService.selectJiajiaOrderList(order).get(0);
        Map<String, String> params = ProfitSharingModel.builder()
                .mch_id(myWxPayConfig.getMchID())
                .appid(myWxPayConfig.getAppID())
                .nonce_str(WxPayKit.generateStr())
                .transaction_id(jiajiaOrder.getTransactionId())
                .out_order_no(jiajiaOrder.getOrderSn())
                .build()
                .createSign(wxPayXiaoChengXuConfig.getMckKey(), SignType.MD5);
        return WxPayApi.profitSharingReturnQuery(params);    }

    @Override
    public AjaxResult withdrawal(Integer amount) {
        String withdrawal = CacheUtils.get(Constants.SYS_CONFIG_CACHE, Constants.SYS_CONFIG_KEY + SysConfigConstants.sys_withdrawal_income_limit).toString();
        Integer remainder=   amount% Integer.valueOf(withdrawal);
        if(remainder == 0){
            //换算单位
            BigDecimal bigDecimal = new BigDecimal(amount * 100);
            JiajiaUser jiajiaUser = userService.selectJiajiaUserById(TokenUtil.getUid());
             if(jiajiaUser.getMoney().compareTo(bigDecimal)>=0){
                 //修改余额
                 jiajiaUser.setMoney(jiajiaUser.getMoney().subtract(bigDecimal));
                 userService.updateJiajiaUser(jiajiaUser);
                 //打款
                 TransferBillsVo transferBillsVo=new TransferBillsVo();
                 //转账唯一号
                 transferBillsVo.setOutBillNo(WxPayKit.generateStr());
                 //转账金额
                 transferBillsVo.setTransferAmount(Integer.valueOf(bigDecimal.toString()));
                 //转账备注
                 transferBillsVo.setTransferRemark("用户："+TokenUtil.getUid()+"提现");

                 List<TransferSceneReportInfo> list=new ArrayList<>();
                 TransferSceneReportInfo transferSceneReportInfo=new TransferSceneReportInfo();
                 TransferSceneReportInfo transferSceneReportInfo1=new TransferSceneReportInfo();

                 transferSceneReportInfo.setInfoType("活动名称");
                 transferSceneReportInfo.setInfoContent("推广有奖");

                 transferSceneReportInfo1.setInfoType("奖励说明");
                 transferSceneReportInfo1.setInfoContent("用户提现");
                 list.add(transferSceneReportInfo);
                 list.add(transferSceneReportInfo1);
                 transferBillsVo.setTransferSceneReportInfos(list);
                 transferBillsVo.setOrderType("4");
                 transferBillsVo.setUserId(jiajiaUser.getId());
                 //转账用户
                 String openId="";
                 if(Optional.ofNullable(jiajiaUser.getOpenId()).isPresent() && !jiajiaUser.getOpenId().equals("")){
                     openId=jiajiaUser.getOpenId();
                     transferBillsVo.setPaymentChannels(TokenUtil.platforms_MP);

                 }else if(Optional.ofNullable(jiajiaUser.getGzhOpenId()).isPresent()&& !jiajiaUser.getGzhOpenId().equals("")){
                     openId=jiajiaUser.getGzhOpenId();
                     transferBillsVo.setPaymentChannels(TokenUtil.platforms_H5);


                 }else{
                     openId=jiajiaUser.getAppOpenId();
                     transferBillsVo.setPaymentChannels(TokenUtil.platforms_APP);


                 }
                 transferBillsVo.setOpenid(openId);

                 V3PayUtil.createTransferBills(transferBillsVo);
                 //转账入库
                 JiajiaTransferAccounts jiajiaTransferAccounts=new JiajiaTransferAccounts();
                 BeanUtils.copyProperties(transferBillsVo,jiajiaTransferAccounts);
                 JSONObject returnJSONObject = transferBillsVo.getReturnJSONObject();
                 jiajiaTransferAccounts.setState(returnJSONObject.getString("state"));
                 jiajiaTransferAccounts.setTransferBillNo(returnJSONObject.getString("transfer_bill_no"));
                 jiajiaTransferAccounts.setPackageInfo(returnJSONObject.getString("package_info"));
                 jiajiaTransferAccounts.setVersion(LocalDateTime.now()+String.valueOf(Math.random()));
                 jiajiaTransferAccounts.setPaymentChannels(transferBillsVo.getPaymentChannels());
                 jiajiaTransferAccounts.setDeleted("0");
                 jiajiaTransferAccountsService.insertJiajiaTransferAccounts(jiajiaTransferAccounts);

                 return     AjaxResult.success(jiajiaTransferAccounts);

              }else{
                 return     AjaxResult.error("提现金额不能大于余额");

             }

        }else{
            return  AjaxResult.error("提现金额为："+withdrawal+"的整数倍，请重新输入提现金额");
        }


    }

    @Override
    public AjaxResult selectTransferAccounts(Long id) {
            //用户操作数据
                JiajiaTransferAccounts jiajiaTransferAccounts = jiajiaTransferAccountsService.selectJiajiaTransferAccountsById(id);
                V3PayUtil.selectTransfer(jiajiaTransferAccounts.getTransferBillNo());


        return null;
    }


    /**
     * 代理分账
     * @param openid
     * @param amount
     * @param transactionId
     * @param orderSn
     * @return
     */
    @Override
    public String profitSharingByProxy(String  openid,Integer amount,String transactionId, String orderSn) {
        String orderId =null;
        boolean flag=true;
        while(flag){
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            List<ReceiverModel> listReceiver = new ArrayList<>();
            profitSharingAddReceiver(openid);
            ReceiverModel build = ReceiverModel.builder()
                    .type("PERSONAL_OPENID")
                    .account(openid)
                    .amount(amount)
                    .description("代理分账")
                    .build();
            listReceiver.add(build);

            Map<String, String> params = ProfitSharingModel.builder()
                    .mch_id(myWxPayConfig.getMchID())
                    .appid(myWxPayConfig.getAppID())
                    .nonce_str(WxPayKit.generateStr())
                    .transaction_id(transactionId)
                    .out_order_no(orderSn)
                    .receivers(JSON.toJSONString(listReceiver))
                    .build()
                    .createSign(wxPayXiaoChengXuConfig.getMckKey(), SignType.HMACSHA256);

            logger.info("请求参数:{}", WxPayKit.toXml(params));
            String refundStr = HttpKit.getDelegate().post(WxPayApi.getReqUrl(WxApiType.PROFIT_SHARING), WxPayKit.toXml(params), wxPayXiaoChengXuConfig.getKeyPath(), myWxPayConfig.getMchID(), "");
            logger.info("请求结果:{}", refundStr);

            Map<String, String> stringStringMap = WxPayKit.xmlToMap(refundStr);
            if(stringStringMap.get("return_code").equals("SUCCESS") && stringStringMap.get("result_code").equals("SUCCESS")){
                orderId=stringStringMap.get("order_id");
                flag=false;
            }

        }


        return orderId;
    }
    //判断用户是否为普通用户
    public boolean isOrdinary(JiajiaUser user ) {
            Long id = user.getId();
            JiajiaProxyApplication jiajiaProxyApplication=new JiajiaProxyApplication();
            jiajiaProxyApplication.setStatus(1);
            jiajiaProxyApplication.setUserId(id);
            List<JiajiaProxyApplication> jiajiaProxyApplications = jiajiaProxyApplicationService.selectJiajiaProxyApplicationList(jiajiaProxyApplication);
            if(Optional.ofNullable(jiajiaProxyApplications).isPresent() && jiajiaProxyApplications.size()>0){
                return true;
            }

        return false;
    }




}
